package com.xxl.job.executor.service.jobhandler;

import com.xxl.job.executor.entity.JobResultDTO;
import com.xxl.job.executor.util.CrontabUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wenhonghao
 * @email 18167784149@163.com
 * @description: 返回回调结果
 */
@Service
public class ExecutorCallbackService {
    @Value("${xxl.job.admin.addresses}")
    private String adminUrl;

    @Value("${xxl.job.accessToken}")
    private String authToken;

    private final RestTemplate restTemplate;


    public ExecutorCallbackService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 发送任务执行结果回调调度中心
     * @param jobResultDTO 回调的任务结果对象
     * @return 调度中心的响应
     */
    public ResponseEntity<Map<String, Object>> sendResultToScheduler(JobResultDTO jobResultDTO,String sessionId) {
        String schedulerCallbackUrl = adminUrl + "/job-result/receive";

        try {
            System.out.println("*********回调函数被调用********");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            headers.add(HttpHeaders.COOKIE, "XXL_JOB_LOGIN_IDENTITY=" + sessionId);
            headers.setContentType(MediaType.APPLICATION_JSON);  // 设置 Content-Type 为 JSON

            HttpEntity<JobResultDTO> requestEntity = new HttpEntity<>(jobResultDTO, headers);
            System.out.println(headers);
            // 调用调度中心的回调接口
            ResponseEntity<Map<String, Object>> response = restTemplate.exchange(
                    schedulerCallbackUrl,                          // 请求的URL
                    HttpMethod.POST,                               // 请求方法
                    requestEntity,                // 请求实体，包含发送的数据
                    new ParameterizedTypeReference<Map<String, Object>>() {}  // 目标返回值类型
            );
            return response;
        } catch (Exception e) {
            // 处理异常情况
            System.err.println("调度中心回调失败: " + e.getMessage());
            // 创建HashMap并手动添加键值对
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "调度中心回调失败");

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    public ResponseEntity<Map<String, Object>> initCrontab(JobResultDTO jobResultDTO,String sessionId) {
        String schedulerCallbackUrl = adminUrl + "/job-result/init";

        try {
            System.out.println("*********初始化回调函数被调用********");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            headers.add(HttpHeaders.COOKIE, "XXL_JOB_LOGIN_IDENTITY=" + sessionId);
            headers.setContentType(MediaType.APPLICATION_JSON);  // 设置 Content-Type 为 JSON

            HttpEntity<JobResultDTO> requestEntity = new HttpEntity<>(jobResultDTO, headers);
            System.out.println(headers);
            // 调用调度中心的回调接口
            ResponseEntity<Map<String, Object>> response = restTemplate.exchange(
                    schedulerCallbackUrl,                          // 请求的URL
                    HttpMethod.POST,                               // 请求方法
                    requestEntity,                // 请求实体，包含发送的数据
                    new ParameterizedTypeReference<Map<String, Object>>() {}  // 目标返回值类型
            );
            return response;
        } catch (Exception e) {
            // 处理异常情况
            System.err.println("调度中心回调失败: " + e.getMessage());
            // 创建HashMap并手动添加键值对
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "调度中心回调失败");

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
}
